package cn.edu.live.dao;

import java.sql.SQLException;

import cn.edu.live.model.UserInfo;
import cn.edu.live.util.TimeUtil;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

public class UserDao {

	/**
	 * 顺序使用参数id，username，usermail，优先使用第一个且仅使用一个有效参数来查询。(此方法不区分type)
	 * 
	 * 此处不允许用户的username，uesrmail有重复
	 * 
	 * 无效参数：id=0，username=null，usermail=null
	 * 
	 * @param id
	 * @param username
	 * @param usermail
	 * @return
	 */
	public UserInfo findUesrInfo(int id, String username, String usermail) {
		String sql = null;

		if (id != 0) {
			sql = "select * from userinfo where id = ?";
			return UserInfo.dao.findFirst(sql, id);
		}
		if (username != null) {
			sql = "select * from userinfo where username = ?";
			return UserInfo.dao.findFirst(sql, username);
		}
		if (usermail != null) {
			sql = "select * from userinfo where usermail = ?";
			return UserInfo.dao.findFirst(sql, usermail);
		}
		return null;
	}

	/**
	 * 保存注册用户信息，使用事务支持。 若成功则同时在2个表中新建记录。type为1或者2
	 * 
	 * type:1-->student，2-->anchor
	 * 
	 * @param username
	 * @param password
	 * @param usermail
	 * @param type
	 */
	@Before(Tx.class)
	public boolean saveUser(final String username, final String password, final String usermail, final int type) {
		return Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				UserInfo ui = new UserInfo().set("username", username).set("password", password)
						.set("usermail", usermail).set("type", type);
				boolean isSaved = ui.save();
				if (isSaved) {
					Record record = new Record().set("username", username).set("usermail", usermail)
							.set("infoid", ui.getInt("id")).set("registTime", TimeUtil.currentTime());
					String tableNameString = (type == 1 ? "student" : "anchor");
					return Db.save(tableNameString, record);
				} else {
					return false;
				}

			}
		});

	}

}
